﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TextAnalytics.Models;

namespace TextAnalytics.Operations
{
    public static class ProjectOperations
    {
        public static ProjectModel CreateNewProject(string name, string rootDirectoryPath, bool createDirectoryForProject = true)
        {
            var result = new ProjectModel();
            result.Name = name;
            if (createDirectoryForProject)
            {
                rootDirectoryPath = Path.Combine(rootDirectoryPath, name);
            }
            result.RootDirectoryPath = rootDirectoryPath;
            result.DataDirectoryPath = Path.Combine(Path.Combine(rootDirectoryPath, "Data"));

            if (Directory.Exists(result.DataDirectoryPath))
            {
                var projectFileExists = File.Exists(result.GetProjectPath());
                var dbFileExists = File.Exists(result.GetDbPath());

                if (projectFileExists || dbFileExists)
                {
                    throw new ProjectAlreadyExistsException();
                }
            }

            Directory.CreateDirectory(result.RootDirectoryPath);

            result.RootDirectory = DirectoryModel.LoadFromPath(result.RootDirectoryPath);

            Directory.CreateDirectory(result.DataDirectoryPath);

            var builder = new SQLiteConnectionStringBuilder();
            builder.Version = 3;
            builder.DataSource = result.GetDbPath();
            builder.FailIfMissing = false;
            //TODO: Password protect

            using (SQLiteConnection con = new SQLiteConnection(builder.ToString()))
            {
                con.Open();
            }

            result.Save();
            return result;
        }
        public static ProjectModel OpenExistingProject(string projectFilePath)
        {
            return ProjectModel.Load(projectFilePath);
        }

    }

    public class ProjectAlreadyExistsException : Exception
    {

    }
}
